package com.codewsq;

import org.junit.Test;
import sun.java2d.pipe.SpanIterator;

import java.util.*;

public class MapTest {

    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put("key", "haha");
        Object put = map.put("key", "value");

        System.out.println(put);

        map.put("k2", "value2");

        Object key = map.get("key");
        System.out.println(key);


        Set<Map.Entry> set = map.entrySet();

        Iterator<Map.Entry> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

    @Test
    public void test1() {
        HashMap<String, String> map = new HashMap();
        map.put("10001", "haha");
        map.put("10002", "heihei");
        map.put("10003", "hehehe");
        map.put("10004", "haha");
        map.put("10005", "haha");

        List<String> keys = getKeys(map, "haha");
        System.out.println(keys);
    }

    /**
     * 根据value获取map的key
     *
     * @param map   map集合
     * @param value 目标值
     * @return java.util.List<T>
     * @author codewsq
     * @date 2022/4/20 0020 17:48
     */
    public static <K, T> List<K> getKeys(Map<K, T> map, T value) {
        List<K> resultKey = new ArrayList<>();
        Set<K> keySet = map.keySet();
        for (K key : keySet) {
            if (value.equals(map.get(key))) {
                resultKey.add(key);
            }
        }
        return resultKey;
    }

    @Test
    public void test2() {
        HashMap<String, String> map = new HashMap();
        map.put("10001", "haha");
        map.put("10002", "heihei");
        map.put("10003", "hehehe");
        map.put("10004", "haha");
        map.put("10005", "haha");
        // boolean containsKey(key): 判断map是否存在指定key，存在则true，不存在则false
        System.out.println(map.containsKey("10001"));
        System.out.println(map.containsKey("20001"));
    }


    @Test
    public void test4() {
        int i = 0;
        try {
            if (i == 0) {
                return;
            }
            System.out.println("try....");
        } catch (Exception e) {
            System.out.println("catch....");
        } finally {
            System.out.println("finally....");
        }
    }
}
